import {messages} from "share/common";
import React from 'react';
import { connect } from "react-redux";
import { Menu, Layout, Select, message, Alert, Input, Spin } from 'antd';
const { SubMenu, Item } = Menu;
const { Header, Sider, Content } = Layout;
const { Option } = Select;
const { Search } = Input;
import 'styles/setting/allocate-center/allocate-center.scss'
import baseService from 'share/base.service';
import PaymentDesk from "containers/setting/allocate-center/payment-desk";
import AllocateServices from 'containers/setting/allocate-center/allocate-services'

class AllocateCenter extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      setOfBooks: [],
      setOfBooksId: props.company.setOfBooksId,
      menus: [],
      openKeys: ['PAYMENT'],
      selectedKeys: ['PAYMENT_1'],
      searchKey: '',
      loading: false
    };
  }

  componentWillMount(){
    this.getSetOfBook();
    this.getMenus();
  }

  getMenus = () => {
    this.setState({ loading: true });
    AllocateServices.getMenuList().then(res => {
      this.setState({ loading: false, menus: this.handleMenuData(res.data) });
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    });
  };

  handleMenuData = data => {
    let temp = [];
    Object.keys(data).map(item => {
      let subMenu = {
        name: item,
        options: []
      };
      data[item].map(it => {
        let menuItem = {
          name: it.showName,
          key: it.categoryItem
        };
        subMenu.key = it.categoryItem.split('_')[0];
        subMenu.options.push(menuItem);
      });
      temp.push(subMenu);
    });
    return temp;
  };

  handleClickMenu = e => {
    this.setState({ selectedKeys: [e.key] });
  };

  getSetOfBook = () => {
    baseService.getSetOfBooksByTenant().then(res => {
      this.setState({ setOfBooks: res.data })
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  handleChangeBookId = value => {
    this.setState({ setOfBooksId: value },() => {

    });
  };

  handleChangeKey = value => {
    let key = value.target.value;
    const { menus } = this.state;
    if (key && key !== '') {
      let temp = [];
      let selectKey = [];
      menus.map(item => {
        let tempArray = item.options.filter(it => it.name.indexOf(key) > -1);
        if (tempArray.length) {
          if (temp.length === 0) {
            selectKey.push(tempArray[0].key);
          }
          temp.push(item.key);
        }
      });
      this.setState({ openKeys: temp, selectedKeys: selectKey, searchKey: key }, () => {
        this.refs.searchInput.focus();
      })
    } else {
      this.setState({ searchKey: '' });
    }
  };

  handleOpenKeys = openKeys => {
    this.setState({ openKeys });
  };

  renderName = str => {
    const { searchKey } = this.state;
    let result = [];
    let sections = str.split(searchKey);
    sections.map((item, index) => {
      result.push(item);
      if(index !== sections.length - 1){
        result.push(<span className={'target-key'} key={index}>{searchKey}</span>)
      }
    });
    return result;
  };

  render(){
    const { setOfBooks, menus, setOfBooksId, openKeys, selectedKeys, loading } = this.state;
    const {company} = this.props;
    return (
      <Spin spinning={loading}>
        <Layout className={'allocate-center'}>
          <Header className={'allocate-center-title'}>
            {messages('setting.key2144')/*帐套：*/}
            <Select onChange={e => this.handleChangeBookId(e)} defaultValue={company.setOfBooksName}>
              {
                setOfBooks.map(item => {
                  return <Option key={item.id} title={item.setOfBooksName}>{item.setOfBooksName}</Option>
                })
              }
            </Select>
            <Alert
              type={'info'}
              className={'alert-title'}
              showIcon
              message={messages('setting.key2145')/*配置了规则时，按照规则执行，否则按照默认规则执行；*/}
            />
          </Header>
          <Layout>
            <Sider style={{ width: 200, backgroundColor: '#fff' }}>
              <Search
                style={{ display: 'block', margin: '0px 10px 10px 13px', width: '177px' }}
                onChange={this.handleChangeKey}
                ref={'searchInput'}
                placeholder={messages('common.please.input')/*请输入*/}
              />
              <Menu
                mode="inline"
                openKeys={openKeys}
                onOpenChange={this.handleOpenKeys}
                selectedKeys={selectedKeys}
                style={{ minHeight: 'calc(100vh - 222px)' }}
                onClick={this.handleClickMenu}
              >
                {
                  menus.map(item => {
                    return <SubMenu key={item.key} title={item.name}>
                      {
                        item.options.map(it => <Item key={it.key}>{this.renderName(it.name)}</Item>)
                      }
                    </SubMenu>
                  })
                }
              </Menu>
            </Sider>
            <Layout>
              <Content style={{ minHeight: 'calc(100vh - 180px)', backgroundColor: '#fff', padding: '0px 20px' }}>
                {
                  selectedKeys.length > 0 ? <PaymentDesk setOfBooksId={setOfBooksId} categoryItemCode={selectedKeys[0]}/> : ''
                }
              </Content>
            </Layout>
          </Layout>
        </Layout>
      </Spin>
    )
  }
}

function mapStateToProps(state){
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(AllocateCenter);
